<?php

namespace Modules\Asset\Entities;

use Illuminate\Database\Eloquent\Builder;
use \Modules\Order\Entities\BaseOrder;

use \Modules\Asset\Entities\Resale;

use ThrowException;
use Setting;

// 发货订单
class ResaleOrder extends BaseOrder
{
    protected $guarded = [];
    protected $table = 'orders';

    static public $resourceName = '转售订单';
    static public $orderType = 'resale';

    public $isAutoComplete = true;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('assetOrder', function(Builder $builder) {
            $builder->type('resale');
        });
    }

    public function generateNumber()
    {
        $number = 'R' . date('ymdHis') . $this->user_id . '0' . rand(10000, 99999);
        return $number;
    }


    // 支付成功回调
    public function paidListenerSync()
    {
        $resaleId = @$this->options['resale_id'];

        if ($resaleId) {

            $resale = Resale::getEntity([
                'id' => $resaleId
            ]);

            // 完成转售
            if ($resale) {
                $resale->complete($this);
            }
        }

        return true;

        // $this->ticket->pay_status = 1;
        // $this->ticket->save();

        // $this->autoFreight();
        // \Log::error('package order pay: ' . $this->id);
    }

    // 订单关闭, 释放转售的冻结状态
    public function closedSync()
    {
    	$resaleId = @$this->options['resale_id'];

        if ($resaleId) {

            $resale = Resale::getEntity([
                'id' => $resaleId
            ]);

            // 完成转售
            if ($resale) {
            	// 
                $resale->update([
		            'pending_at' => null,
		            'buyer_id'  => null,
		            'status' => 1
		        ]);
            }
        }
    }
}
